import { WebSocket } from "ws";
import { User } from "../../../types/User";
import { roomsTable } from "../../../database/rooms-table";
import { conversionMessage } from "../helpers/message-converter";
import { SetDeadMessageData } from "../types/MessageData";

export default ({ user, payload }: { client: WebSocket; user: User; payload: SetDeadMessageData["payload"] }) => {
	const room = roomsTable.rooms.find((v) => v.roomId == payload.roomId);
	const player = room?.players.find((v) => v.user.userId == user.userId);
	if (room && player) {
		player.dead = payload.dead;
		if (player.dead) {
			room.discardCards.push(...player.handCards.splice(0, player.handCards.length));
			room.discardCards.push(...player.materielCards.splice(0, player.materielCards.length));
			room.discardCards.push(...player.delayedCards.splice(0, player.delayedCards.length));
			room.discardCards.push(...player.buckleCards.splice(0, player.buckleCards.length));
			player.marks.forEach((v) => {
				if (v.card) room.discardCards.push(v.card);
			});
			player.marks.length = 0;
			player.hiddenHeroIds = [];
			player.flipped = false;
			player.health = 0;
			player.tied = false;
		}
		room.players.forEach((v) => v.client!.send(conversionMessage({ type: "setedDead", payload: null })));
		const log = { userId: user.userId, username: user.username, log: "设置死亡状态，当前为" + (player.dead ? "死亡" : "存活") + "。" };
		room.logs.push(log);
		room.players.forEach((v) => v.client!.send(conversionMessage({ type: "roomLog", payload: log })));
	}
};
